'use strict';

module.exports = {
  ok(data, msg) {
    if (data == undefined && msg == undefined) {
      this.body = {code: 0, msg: '操作成功'};
      return;
    }
    if (msg == undefined) {
      this.body = {code: 0, msg: '', data};
      return;
    }
    if (data == undefined) {
      this.body = {code: 0, msg};
      return;
    }
    this.body = {code: 0, msg, data};
    return;
  },

  fail(code, msg, errData) {
    this.body = {code, msg, ...errData};
  },

  val(key) {
    const method = this.request.method;
    if (method == 'GET') {
      return (this.query[key] !== undefined) ? this.query[key] : undefined;
    } else {
      return (this.request.body[key] !== undefined) ? this.request.body[key] : undefined;
    }
  },

  vals() {
    const method = this.request.method;
    if (method == 'GET') {
      return this.query;
    } else {
      return this.request.body;
    }
  },


  err(condition, msg) {
    if (condition) {
      throw new Error(msg);
    }
  },


  async renderX(name, locals = {}, options) {
    const ua = this.headers['user-agent']?.toLocaleLowerCase() || '';
    const isMobile = ua.includes('iphone') || ua.includes('ipad') || ua.includes('android');

    // 根据 UA 确定模板路径和 ua 值
    const templatePrefix = isMobile ? 'mobile' : 'pc';
    locals.ua = isMobile ? 'mobile' : 'pc';

    const templateName = `${templatePrefix}/${name}`;

    return await this.render(templateName, locals, options);
  }


};
